<template>
	<view class="order">
		<header class="order_header" :style="{paddingTop: `${customBar}px`}">
			<image 
				class="bg-img" 
				:style="{height: `calc(220rpx + ${customBar}px)`}" 
				:src="regionBgcUrl[region]" 
				mode="aspectFill">
			</image>
			<view class="organization_wrap">
				<view class="org_info">
					<image class="logo" src="@/static/logo.png" mode="aspectFit"></image>
					<p>益而益集团</p>
					<view @click="isShowRegion = true" style="font-size: 32rpx;margin-left: auto;">
						<span style="margin-right: 5rpx;">
							{{region}}
						</span> 
						<van-icon name="arrow-down" color="black" />
					</view>
				</view>
				<view class="desc">
					益而益集团（ELEGRP）创立于2000年，是一家集漏电保护器、接线装置、智能家居、电线电缆与家用水泵为一体的全球领先的智能化电气与机电设备制造商。
				</view>
				<view class="notice" v-if="publicInfo.announcement">
					<van-notice-bar
					  left-icon="volume-o"
					  :text="publicInfo.announcement"
					/>
				</view>
			</view>
		</header>
		<unicloud-db ref="udb" loadtime="manual" v-slot:default="{data, pagination, loading, hasMore, error}" :collection="collectionList" :where="where" page-size="1000" @load="hanldeData">
		  <view v-if="error">{{error.message}}</view>
		  <view v-else-if="dataList" class="wrap">
				<sideBarVue @on-click-side="handleClickSide" :headerHeight="headerHeight" />
				<section style="flex: 1">
					<listVue ref="listVue" :loading="loading" :customBar="customBar" :headerHeight="headerHeight" :hasMore="hasMore" @onReloadData="reloadData" />
				</section>
		  </view>
		</unicloud-db>
		<submitBlockVue @onShoppingCart="showShoppingCart" />
		<van-popup
		  round
		  :show="isShowShoppingCart && shoppingCart.length"
			close-on-click-overlay
		  position="bottom"
		  custom-style="height: 900rpx"
			@click-overlay="isShowShoppingCart = false"
		>
			<shoppingCartVue />
		</van-popup>
		
		<van-popup
		  :show="isShowRegion"
		  round
		  position="bottom"
			lock-scroll
			@click-overlay="verifySelectRoom() && (isShowRegion = false)"
			zIndex="1000"
		>
			<view class="select_header">
				<p></p>
				<span>选择就餐场所(可多选)</span>
				<p @click="handledSelectRoom">确定</p>
			</view>
			<van-tree-select
			  :items="handledRoomList"
			  height="65vh"
				:main-active-index="regionActive"
			  @click-nav="onClickNav"
			>
				<template #content>
					<selectRegionRoomWrapVue :regionActive="regionActive" @onChange="handleSelectRoomChange" />
				</template>
			</van-tree-select>
		</van-popup>
	</view>
</template>

<script>
	import {mapState, mapGetters, mapMutations} from 'vuex'
	import listVue from './cpns/list.vue'
	import roomCardVue from './cpns/room-card.vue'
	import selectRegionRoomWrapVue from './cpns/select-region-room-wrap.vue'
	import shoppingCartVue from './cpns/shoppingCart.vue'
	import sideBarVue from './cpns/side-bar.vue'
	import submitBlockVue from './cpns/submit-block.vue'
	import {hyh_showModal} from '@/utils/hyh_uni_utils.js'
	const db = uniCloud.database()
	const goodListDB = db.collection('dish-list')
	export default {
		data() {
			return {
				loadMore: {
				  contentdown: '',
				  contentrefresh: '',
				  contentnomore: '',
				},
				regionBgcUrl: {
					'苏州': 'https://mp-c89482b4-9ff9-4c8b-9df7-e6ca01127a34.cdn.bspapp.com/banner/weixintupian_20220728104607-s.png',
					'温州': 'https://mp-c89482b4-9ff9-4c8b-9df7-e6ca01127a34.cdn.bspapp.com/banner/banner20230719.jpg'
				},
				isShowShoppingCart: false,
				isShowRegion: true,
				customBar: 0,
				headerHeight: 0,
				regionActive: 0,
				indentId: undefined,
				shareFlag: true
			}
		},
		components: {
			listVue,
			sideBarVue,
			submitBlockVue,
			shoppingCartVue,
			roomCardVue,
			selectRegionRoomWrapVue
		},
		computed: {
			...mapState({
				dataList: s => s.order.dataList,
				region: s => s.order.region,
				userInfo: s => s.user.userInfo,
				selectedRooms: s => s.order.selectedRooms,
				roomCheckedByID: s => s.order.roomCheckedByID,
				publicInfo: s => s.user.publicInfo
			}),
			...mapGetters(['shoppingCart', 'handledRoomList']),
			roomIsselect() {
				return [this.roomCheckedByID, this.selectedRooms]
			},
			where() {
				if (!this.selectedRooms.length) return ''
				const place_type = this.selectedRooms[0].place_type
				return `category_id.place_type in [\"${place_type}\"]`
			},
			collectionList() {
				const {region, userInfo} = this
				const role_id = userInfo?.role?.[0]?.role_id
				const dish_permission = role_id ? `&& "${role_id}" in dish_permission` : ''
				return [
					db.collection('dish-list')
						.where(`is_on_sale == true && "${region}" in region ${dish_permission}`)
						.orderBy('order')
						.getTemp(),
					db.collection('dish-categories')
						.field('sort, is_hot_show, place_type, name as text, _id')
						.getTemp(),
					db.collection('dish-role')
						.field('role_name as text, role_id')
						.getTemp() 
				]
			}
		},
		onLoad(e) {
			this.indentId = e.indentId
			uni.setTabBarStyle({borderStyle: 'white'})
			uni.showShareMenu()
			uni.$once('initUserInfo_end', () => {
				this.$nextTick(() => {
					this.reloadData()
				})
			})
			uni.$on('reloadDishData', this.reloadData.bind(this))
			uni.$on('oneMoreRrder', this.oneMoreRrder.bind(this))
			uni.$on('continueOrder', this.continueOrder.bind(this))
			wx.getSystemInfo({
				 success: e => {
					 const capsule = wx.getMenuButtonBoundingClientRect();
					 this.customBar = capsule.bottom + capsule.top - e.statusBarHeight;
				 }
		 })
		 this.$store.dispatch('requestRoomList')
		 const region = uni.getStorageSync('region')
		 this.setRegion(region || this.region)
		},
		mounted() {
			wx.createSelectorQuery().in(this)
				.select('.order_header')
				.boundingClientRect()
				.exec((res) => {
					this.headerHeight = res[0].height
				})
		},
		methods: {
			...mapMutations(['setRegion', 'setRegionActive', 'setSelectedRooms', 'setRoomCheckedByID', 'setShareOrderTimer', 'setShareIndent']),
			async handleShare(id) {
				const indent = await this.getShareIndent(id)
				this.continueOrder(indent)
			},
			async getShareIndent(id) {
				const collectionList = [
					db.collection('dish-order-form').where('_id=="' + id + '"').getTemp(),
					db.collection('dish-user').field('openid,nickname as text,avatar_url,phone,status,role,sex,push_clientid,create_time,last_login_date').getTemp(),
					db.collection('dish-role').field('role_name as text, role_id').getTemp(),
					db.collection('dish-dining-place').field('name as text, _id').getTemp(),
					db.collection('dish-order-form-goods').getTemp(),
					db.collection('dish-order-form-guest-type').getTemp(),
				]
				const indentRes = await db.collection(...collectionList).get()
				return indentRes.result.data[0]
			},
			async continueOrder(indent) {
				this.oneMoreRrder(indent)
				const timer = setInterval(this.continueOrderInterval.bind(this, indent), 3000)
				this.setShareOrderTimer(timer)
				this.setShareIndent(indent)
			},
			async continueOrderInterval(indent){
				// this.reloadData() 请求订单
				const indent_ = await this.getShareIndent(indent._id)
				
				// -----------------------------------
				const orderGoods = indent_.order_form_num['dish-order-form-goods']
				this.$store.commit('clearShoppingCart', this.shoppingCart)
				this.regionActive = this.handledRoomList.findIndex(e => e.text === indent_.region)
				this.setRoomCheckedByID(indent_.dining_place.map(e => e._id))
				
				const active = this.handledRoomList[this.regionActive]
				this.setRegion(active.text)
				this.setSelectedRooms(active.children.filter(e => this.roomCheckedByID.includes(e._id)))
				
				this.dataList.forEach((e, i) => {
					const item = orderGoods[i]
					if (!item || !e) return
					if (e.specification?.length) {
						const goods = {
							...e,
							num: item.goods_num,
							specificationSelected: item.specification_selected.split(', ')
						}
						this.$store.commit('setSpecificationList', [goods, item.goods_num])
					} else {
						this.$store.commit('changeGoodsNumByID', [item.goods_id, item.goods_num])
					}
				})
				
				setTimeout(() => {
					uni.$emit('getElOffSetTop')
				}, 200)
			},
			async oneMoreRrder(indent) {
				this.$store.commit('clearShoppingCart', this.shoppingCart)
				this.regionActive = this.handledRoomList.findIndex(e => e.text === indent.region)
				this.setRoomCheckedByID(indent.dining_place.map(e => e._id))
				
				const active = this.handledRoomList[this.regionActive]
				this.setRegion(active.text)
				this.setSelectedRooms(active.children.filter(e => this.roomCheckedByID.includes(e._id)))
				await this.$nextTick()
				this.reloadData(async () => {
					await this.$nextTick()
					const {region, userInfo} = this
					const role_id = userInfo?.role?.[0]?.role_id
					const dish_permission = role_id ? `&& "${role_id}" in dish_permission` : ''
					
					const orderGoods = indent.order_form_num['dish-order-form-goods']
					const goods_id_list = orderGoods.map(e => e.goods_id)
					const goods_id_list_where = goods_id_list.map(e => `\"${e}\"`)
					const goods = await goodListDB.where(`_id in [${goods_id_list_where.join(",")}] && is_on_sale == true && "${region}" in region ${dish_permission}`).get()
						.then(r => r.result.data)
					const issueGoods = []
					const goodsList = orderGoods.map(e => {
						const item = goods.find(v => e.goods_id === v._id)
						if (item && item.remain_count) {
							return item
						} else {
							issueGoods.push(e.goods_name)
						}
					})
					goodsList.forEach((e, i) => {
						const item = orderGoods[i]
						if (!item || !e) return
						if (e.specification?.length) {
							const goods = {
								...e,
								num: item.goods_num,
								specificationSelected: item.specification_selected.split(', ')
							}
							this.$store.commit('setSpecificationList', [goods, item.goods_num])
						} else {
							this.$store.commit('changeGoodsNumByID', [item.goods_id, item.goods_num])
						}
					})
					if (!issueGoods.length) return
					uni.showModal({
						title: "提示",
						content: `以下商品缺货或已下架 \n ${issueGoods.join('\n')}`,
						showCancel: false
					})
				})
			},
			onClickNav({ detail = {} }) {
				this.regionActive = detail.index
				this.setRoomCheckedByID([])
			},
			handleSelectRoomChange(value) {
				this.setRoomCheckedByID(value)
			},
			async handledSelectRoom() {
				let flag = true
				if (!this.roomCheckedByID.length)
					return uni.showToast({title: '最少选择一个房间',icon: 'none'})
					
				if (this.shoppingCart.length) {
					flag = await hyh_showModal({
						title: '提示',
						content: '更换地区包厢会重置购物车, 是否继续',
					})
				}
				this.isShowRegion = false
				if (!flag) return
				const active = this.handledRoomList[this.regionActive]
				this.setRegion(active.text)
				this.setSelectedRooms(active.children.filter(e => this.roomCheckedByID.includes(e._id)))
				await this.$nextTick()
				this.reloadData()
			},
			verifySelectRoom() {
				const has1 = this.roomCheckedByID.length
				const has2 = this.selectedRooms.length
				if (!has1 && !has2 || has1 && !has2)
					return (uni.showToast({title: '最少选择一个房间',icon: 'none'}), false)
				return true
			},
			hanldeData(data) {
				uni.hideLoading();
				const other = [{text: '其他', sort: Infinity}]
				const mapData = data.reduce((map, it) => {
					const list = it.category_id.length ? it.category_id : other
					it.num = 0
					list.forEach(category => {
						let currentIt;
						for (let e of map.keys()) {
							if (e.text === category.text) {
								currentIt = e
								break
							}
						}
						if (currentIt)
							map.get(currentIt).push(it)
						else 
							map.set(category, [it])
					})
					return map
				}, new Map())
				const dataList = Array.from(mapData)
				dataList.sort((a, b) => a[0].sort - b[0].sort)
				this.$store.commit('setDataList', dataList)
				console.log(dataList);
				this.$nextTick(() => {
					this.$refs.listVue.getElOffSetTop()
					if (this.shareFlag && this.indentId) {
						 this.handleShare(this.indentId)
						 this.shareFlag = false
					}
				})
			},
			handleClickSide(index) {
				this.$refs.listVue.setScrollTop(index)
			},
			showShoppingCart() {
				if (!this.shoppingCart.length) return
				this.isShowShoppingCart = !this.isShowShoppingCart
			},
			reloadData(fn) {
				uni.showLoading({title: '加载中',mask: true});
				this.$refs.udb.loadData({clear: true}, fn)
			}
		},
		watch: {
			shoppingCart: {
				handler(shoppingCart) {
					if (!shoppingCart.length) 
						this.isShowShoppingCart = false
				},
				deep: true
			},
			roomIsselect: {
				handler([a, b]) {
					const has1 = a.length
					const has2 = b.length
					if (!(!has1 && !has2 || has1 && !has2))
						this.isShowRegion = false
				},
				deep: true
			}
		}
	}
</script>

<style lang="scss">
	page {
		--nav-bar-background-color: #004EA2;
		--nav-bar-title-text-color: white;
		--nav-bar-title-font-size: 30rpx;
		--font-weight-bold: 0;
		--notice-bar-height: 38rpx;
		--notice-bar-icon-size: 24rpx;
		--notice-bar-font-size: 24rpx;
		--notice-bar-padding: 0 10rpx;
		--sidebar-background-color: #f2f2f2;
		--tree-select-nav-background-color: #f2f2f2;
		--sidebar-font-size: 30rpx;
	}
	.van-sidebar {
		width: 160rpx !important;
	}
	::-webkit-scrollbar {
	  display: none;
	  width: 0;
	  height: 0;
	  color: transparent;
	}
	
	.order {
		header {
			height: 220rpx;
			padding-bottom: 80rpx;
			position: relative;
			background-color: #fff;
			.bg-img {
				width: 100vw;
				position: absolute;
				left: 0;
				top: 0;
				z-index: 0;
			}
			.organization_wrap {
				width: 95%;
				height: 280rpx;
				border-radius: 20rpx;
				background: linear-gradient(to bottom, rgba(255,255,255,0.5) 0%, rgba(255,255,255,0.9) 30%, rgba(255,255,255,1) 100%);
				position: absolute;
				bottom: 20rpx;
				left: 50%;
				transform: translateX(-50%);
				z-index: inherit;
				box-sizing: border-box;
				padding: 26rpx;
				box-shadow: 0 1px 10rpx #eaeaea;
				
				.org_info {
					display: flex;
					align-items: center;
					height: 100rpx;
					.logo {
						width: 160rpx;
						height: 100rpx;
						background-color: #f7f7f7;
						margin-right: 20rpx;
						padding: 0 6rpx;
						border-radius: 16rpx;
					}
					p {
						font-size: 36rpx;
						color: black;
						font-weight: bold;
					}
				}
				.desc {
					color: #6d6969;
					font-size: 24rpx;
				}
				.notice {
					border-radius: 8rpx;
					overflow: hidden;
					width: 90%;
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					bottom: 4rpx;
				}
			}
		}
		.wrap {
			display: flex;
			
		}
		
		.select_header {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 30rpx;
			border-bottom: 1px solid #f4f4f4;
			p {
				width: 100rpx;
				height: 100%;
				color: #67C23A;
				text-align: center;
				line-height: 100rpx;
			}
		}
	}
</style>
